package ch02;

import org.jcp.xml.dsig.internal.dom.DOMManifest;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.FileOutputStream;

public class LianXi {
    public static void main(String[] args) {
        try {
            //得到DOM解析器的工厂实例
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            //从DOM工厂获得DOM解析器
            DocumentBuilder db = dbf.newDocumentBuilder();
            //解析XML文档，得到一个Document对象，即DOM树
            Document doc = db.parse("src/ch02/LianXi.xml");//收藏信息.xml为保存手机收藏信息的xml文档

//            NodeList list = doc.getElementsByTagName("username");
//            System.out.println(list.item(0).getFirstChild().getNodeValue());

            Element element=doc.createElement("age");
            element.setAttribute("value","18");
            element.setTextContent("18");

            doc.getElementsByTagName("Student").item(0).appendChild(element);
            //保存XMl文件
            TransformerFactory transformerFactory=TransformerFactory.newInstance();
            Transformer transformer=transformerFactory.newTransformer();
            DOMSource domSource=new DOMSource(doc);
            //设置编码类型
            transformer.setOutputProperty(OutputKeys.ENCODING,"utf-8");
            StreamResult result=new StreamResult(new FileOutputStream("src/ch02/LianXi1.xml"));
            transformer.transform(domSource,result);

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
